/**
 * API稳定性测试脚本
 * 用于测试API在高并发情况下的稳定性
 */

const http = require('http')
const { performance } = require('perf_hooks')

// 配置
const config = {
  host: 'localhost',
  port: 7204,
  endpoints: [
    { path: '/api/config', method: 'GET' },
    { path: '/api/typewriter-texts', method: 'GET' },
    { path: '/api/projects?limit=10&page=1', method: 'GET' },
    { path: '/api/blogs?limit=10&page=1', method: 'GET' },
    { path: '/api/tech-stack', method: 'GET' },
    { path: '/health', method: 'GET' },
  ],
  concurrentRequests: 10, // 并发请求数
  rounds: 3, // 测试轮数
  delayBetweenRounds: 2000, // 轮次间隔（毫秒）
}

// 发送单个请求
function sendRequest(endpoint) {
  return new Promise((resolve, reject) => {
    const startTime = performance.now()

    const options = {
      hostname: config.host,
      port: config.port,
      path: endpoint.path,
      method: endpoint.method,
      headers: {
        Accept: 'application/json',
      },
    }

    const req = http.request(options, (res) => {
      const endTime = performance.now()
      const duration = endTime - startTime

      let data = ''

      res.on('data', (chunk) => {
        // 数据接收处理
      })

      res.on('end', () => {
        resolve({
          endpoint: endpoint.path,
          statusCode: res.statusCode,
          duration: duration.toFixed(2),
          headers: res.headers,
          success: res.statusCode >= 200 && res.statusCode < 300,
        })
      })
    })

    req.on('error', (error) => {
      const endTime = performance.now()
      const duration = endTime - startTime

      reject({
        endpoint: endpoint.path,
        error: error.message,
        duration: duration.toFixed(2),
        success: false,
      })
    })

    req.end()
  })
}

// 发送并发请求
async function sendConcurrentRequests(endpoint, count) {
  const promises = []

  for (let i = 0; i < count; i++) {
    promises.push(sendRequest(endpoint))
  }

  try {
    const results = await Promise.all(promises)
    return results
  } catch (error) {
    console.error('并发请求失败:', error)
    return []
  }
}

// 运行测试
async function runTest() {
  console.log('开始API稳定性测试...')
  console.log(`并发请求数: ${config.concurrentRequests}`)
  console.log(`测试轮数: ${config.rounds}`)
  console.log('-----------------------------------')

  const summary = {
    totalRequests: 0,
    successfulRequests: 0,
    failedRequests: 0,
    averageDuration: 0,
    totalDuration: 0,
    statusCodes: {},
  }

  for (let round = 1; round <= config.rounds; round++) {
    console.log(`\n开始第 ${round} 轮测试`)

    for (const endpoint of config.endpoints) {
      console.log(`\n测试端点: ${endpoint.path}`)

      try {
        const results = await sendConcurrentRequests(
          endpoint,
          config.concurrentRequests,
        )

        let roundSuccess = 0
        let roundFailed = 0
        let roundTotalDuration = 0

        for (const result of results) {
          summary.totalRequests++
          roundTotalDuration += parseFloat(result.duration)

          if (result.success) {
            summary.successfulRequests++
            roundSuccess++
          } else {
            summary.failedRequests++
            roundFailed++
          }

          // 记录状态码
          const statusCode = result.statusCode || 'error'
          summary.statusCodes[statusCode] =
            (summary.statusCodes[statusCode] || 0) + 1
        }

        summary.totalDuration += roundTotalDuration

        console.log(`成功: ${roundSuccess}, 失败: ${roundFailed}`)
        console.log(
          `平均响应时间: ${(roundTotalDuration / results.length).toFixed(2)} ms`,
        )
      } catch (error) {
        console.error(`测试端点 ${endpoint.path} 失败:`, error)
      }
    }

    if (round < config.rounds) {
      console.log(
        `\n等待 ${config.delayBetweenRounds / 1000} 秒后开始下一轮测试...`,
      )
      await new Promise((resolve) =>
        setTimeout(resolve, config.delayBetweenRounds),
      )
    }
  }

  // 打印总结
  console.log('\n-----------------------------------')
  console.log('测试总结:')
  console.log(`总请求数: ${summary.totalRequests}`)
  console.log(`成功请求数: ${summary.successfulRequests}`)
  console.log(`失败请求数: ${summary.failedRequests}`)
  console.log(
    `成功率: ${((summary.successfulRequests / summary.totalRequests) * 100).toFixed(2)}%`,
  )
  console.log(
    `平均响应时间: ${(summary.totalDuration / summary.totalRequests).toFixed(2)} ms`,
  )
  console.log('\n状态码分布:')

  for (const statusCode in summary.statusCodes) {
    console.log(`${statusCode}: ${summary.statusCodes[statusCode]} 次`)
  }
}

// 运行测试
runTest().catch((error) => {
  console.error('测试执行失败:', error)
})
